package com.lwlean.test.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lean on 2016/12/7.
 */
public class FastJsonUtil {

    /**
     * 根据json 字符串转换为 map类型
     * @param str
     * @return
     */
    public static Map<String, Object> parseJSONStr2Map(String str){
        Map<String,Object> map= JSON.parseObject(str,HashMap.class);
        for(String key:map.keySet()){
            Object value = map.get(key);
            if(value==null) map.put(key,"");
            if(value instanceof  Number) map.put(key,value.toString());
            if(value instanceof  Boolean) map.put(key,(Boolean)map.get(key)?"true":"false");
            if(value instanceof  Float) map.put(key,value.toString());
            if(value instanceof JSONObject){
                Map<String,Object> subMap = JSON.parseObject(value.toString(), HashMap.class);
                for (String subKey:subMap.keySet()){
                    Object subValue = subMap.get(subKey);
                    if(value==null) subMap.put(subKey,"");
                    if(value instanceof  Number) subMap.put(subKey,subValue.toString());
                    if(value instanceof  Boolean) subMap.put(subKey,(Boolean)subValue?"true":"false");
                    if(value instanceof  Float) subMap.put(subKey,subValue.toString());
                }
                map.put(key,subMap);
            }
            if(value instanceof JSONArray){
                final List<String> strings = JSONArray.parseArray(value.toString(), String.class);
                final Map<String,Object>[] maps = new HashMap[strings.size()];
                for(int i=0;i<strings.size();i++){
                    final String val = strings.get(i).toString();
                    final HashMap subMap = JSON.parseObject(val, HashMap.class);
                    for (Object subKey:subMap.keySet()){
                        Object subValue = subMap.get(subKey);
                        if(value==null) subMap.put(subKey,"");
                        if(value instanceof  Number) subMap.put(subKey,subValue.toString());
                        if(value instanceof  Boolean) subMap.put(subKey,(Boolean)subValue?"true":"false");
                        if(value instanceof  Float) subMap.put(subKey,subValue.toString());
                    }
                    maps[i]=subMap;
                }
                map.put(key,maps);
            }
        }
        return map;
    }
}
